﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 会员统计报表
    /// </summary>
    [Route("admin/report/member")]
    [ApiController]
    public class ReportMemberController : ControllerBase
    {
        private readonly IReportMemberService _reportMemberService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public ReportMemberController(IReportMemberService reportMemberService, IUserService userService, IMapper mapper)
        {
            _reportMemberService = reportMemberService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 获取会员注册统计
        /// 示例：/admin/report/member/register/count
        /// </summary>
        [HttpGet("register/count")]
        [Authorize]
        public async Task<IActionResult> GetRegisterCount([FromQuery] ReportParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportMemberService.GetMemberRegisterCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (DateTime.Compare(x.RegTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.RegTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }

        /// <summary>
        /// 获取会员注册分页
        /// 示例：/admin/report/member/register/list
        /// </summary>
        [HttpGet("register/list")]
        [Authorize]
        [AuthorizeFilter("ReportMember", ActionType.View, "Register")]
        public async Task<IActionResult> GetRegisterList([FromQuery] ReportParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }

            //获取数据列表
            var list = await _reportMemberService.GetMemberRegisterPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (DateTime.Compare(x.RegTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.RegTime, searchParam.EndTime.GetValueOrDefault()) <= 0),
                searchParam.OrderBy ?? "Id,RegTime");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<MembersDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取会员消费统计
        /// 示例：/admin/report/member/amount/count
        /// </summary>
        [HttpGet("amount/count")]
        [Authorize]
        public async Task<IActionResult> GetAmountCount([FromQuery] ReportParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportMemberService.GetMemberAmountCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }

        /// <summary>
        /// 获取会员消费分页
        /// 示例：/admin/report/member/amount/list
        /// </summary>
        [HttpGet("amount/list")]
        [Authorize]
        [AuthorizeFilter("ReportMember", ActionType.View, "Amount")]
        public async Task<IActionResult> GetAmountList([FromQuery] ReportParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }

            //获取数据列表
            var list = await _reportMemberService.GetMemberAmountPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0),
                searchParam.OrderBy ?? "Id,AddTime");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<MemberAmountLogDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 获取会员消费统计
        /// 示例：/merchant/report/member/favorite/count
        /// </summary>
        [HttpGet("/merchant/report/member/favorite/count")]
        [Authorize]
        public async Task<IActionResult> GetFavoriteCount([FromQuery] ReportParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _reportMemberService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportMemberService.GetMemberFavoriteCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }
        #endregion
    }
}
